package com.example.bgdharaniPlayer.service;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;

import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationCompat;
import androidx.core.content.ContextCompat;

import com.example.bgdharaniPlayer.R;
import com.example.bgdharaniPlayer.model.AudioTrack;
import com.example.bgdharaniPlayer.model.Playlist;
import com.example.bgdharaniPlayer.ui.MainActivity;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class MusicService extends Service {
    private static final String TAG = "MusicService";
    private static final int NOTIFICATION_ID = 1;
    private static final String CHANNEL_ID = "MusicServiceChannel";

    private final IBinder binder = new MusicBinder();
    private MediaPlayer mediaPlayer;
    private List<AudioTrack> playlist = new ArrayList<>();
    private int currentTrackIndex = -1;
    private int currentRepeatCount = 0;
    private float volume = 0.5f; // 默认音量为50%
    private boolean isPaused = false;
    private String currentPlaylistId = null; // 当前播放列表ID
    
    // 获取当前重复次数
    public int getCurrentRepeatCount() {
        return currentRepeatCount;
    }
    
    // 获取当前播放列表ID
    public String getPlaylistId() {
        return currentPlaylistId;
    }

    public class MusicBinder extends Binder {
        public MusicService getService() {
            return MusicService.this;
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        initMediaPlayer();
        createNotificationChannel();
        
        // 检查是否有通知权限（Android 13及以上版本需要）
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.POST_NOTIFICATIONS) 
                    == PackageManager.PERMISSION_GRANTED) {
                startForeground(NOTIFICATION_ID, createNotification());
            } else {
                Log.w(TAG, "没有通知权限，无法启动前台服务");
                // 在实际应用中，您可能需要通过MainActivity请求权限
                // 这里我们仍然尝试启动前台服务，但在某些设备上可能会失败
                startForeground(NOTIFICATION_ID, createNotification());
            }
        } else {
            // 对于Android 12及以下版本，不需要特殊权限
            startForeground(NOTIFICATION_ID, createNotification());
        }
    }

    private void initMediaPlayer() {
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setAudioAttributes(
                new AudioAttributes.Builder()
                        .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                        .setUsage(AudioAttributes.USAGE_MEDIA)
                        .build()
        );
        
        mediaPlayer.setOnCompletionListener(mp -> {
            AudioTrack currentTrack = getCurrentTrack();
            if (currentTrack == null) {
                // 如果当前没有曲目，尝试播放下一曲
                Log.w(TAG, "播放完成但当前曲目为空，尝试播放下一曲");
                currentRepeatCount = 0;
                playNext();
                return;
            }
            
            currentRepeatCount++;
            if (currentRepeatCount < currentTrack.getRepeatCount()) {
                // 重复播放当前曲目
                playCurrentTrack();
            } else {
                // 播放下一曲
                currentRepeatCount = 0;
                playNext();
            }
        });
        
        mediaPlayer.setOnErrorListener((mp, what, extra) -> {
            Log.e(TAG, "MediaPlayer error: " + what + ", " + extra);
            return false;
        });
    }

    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                    CHANNEL_ID,
                    "背景音乐服务",
                    NotificationManager.IMPORTANCE_LOW
            );
            channel.setDescription("用于背景音乐播放的通知");
            NotificationManager manager = getSystemService(NotificationManager.class);
            manager.createNotificationChannel(channel);
        }
    }

    private Notification createNotification() {
        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(
                this, 0, notificationIntent, PendingIntent.FLAG_IMMUTABLE);

        String title = "背景音乐播放中";
        String content = currentTrackIndex >= 0 && currentTrackIndex < playlist.size() 
                ? playlist.get(currentTrackIndex).getTitle() : "无播放内容";

        return new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle(title)
                .setContentText(content)
                .setSmallIcon(R.drawable.ic_music_note)
                .setContentIntent(pendingIntent)
                .build();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // 如果服务被系统杀死，重新启动
        return START_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    @Override
    public void onDestroy() {
        if (mediaPlayer != null) {
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.stop();
            }
            mediaPlayer.release();
            mediaPlayer = null;
        }
        super.onDestroy();
    }

    // 设置播放列表
    public void setPlaylist(Playlist playlist) {
        // 保存当前播放状态
        boolean wasPlaying = mediaPlayer != null && mediaPlayer.isPlaying();
        int currentPosition = 0;
        if (wasPlaying) {
            currentPosition = mediaPlayer.getCurrentPosition();
        }
        
        // 停止当前播放
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
            try {
                mediaPlayer.prepare();
            } catch (IOException e) {
                Log.e(TAG, "Error preparing media player: " + e.getMessage());
            }
        }
        
        // 更新所有曲目的播放状态为非播放
        for (AudioTrack t : this.playlist) {
            t.setPlaying(false);
        }
        
        // 设置新播放列表
        this.playlist = playlist.getTracks();
        this.currentPlaylistId = playlist.getId();
        
        Log.d(TAG, "设置播放列表: ID=" + playlist.getId() + ", 名称=" + playlist.getName() + ", 曲目数=" + playlist.getTracks().size());
        
        // 重置播放状态
        currentRepeatCount = 0;
        isPaused = false;
        
        // 如果新播放列表不为空，只设置索引但不自动播放
        if (!this.playlist.isEmpty()) {
            currentTrackIndex = 0;
            // 不再自动播放第一首曲目
        } else {
            currentTrackIndex = -1;
            Log.w(TAG, "设置了空播放列表");
        }
        
        // 更新通知
        updateNotification();
    }
    
    // 更新播放列表但保持当前播放状态
    public void updatePlaylist(Playlist playlist, int currentPlayingIndex) {
        if (playlist == null || playlist.getTracks().isEmpty()) {
            Log.w(TAG, "尝试更新空播放列表，操作被忽略");
            return;
        }
        
        Log.d(TAG, "更新播放列表: ID=" + playlist.getId() + ", 名称=" + playlist.getName() 
              + ", 曲目数=" + playlist.getTracks().size() + ", 当前播放索引=" + currentPlayingIndex);
        
        // 保存当前播放状态
        boolean wasPlaying = mediaPlayer != null && mediaPlayer.isPlaying();
        int currentPosition = 0;
        if (wasPlaying) {
            currentPosition = mediaPlayer.getCurrentPosition();
            mediaPlayer.pause();
        }
        
        // 更新播放列表
        this.playlist = playlist.getTracks();
        this.currentPlaylistId = playlist.getId();
        
        // 设置当前播放索引
        if (currentPlayingIndex >= 0 && currentPlayingIndex < this.playlist.size()) {
            currentTrackIndex = currentPlayingIndex;
        } else if (!this.playlist.isEmpty()) {
            currentTrackIndex = 0;
        } else {
            currentTrackIndex = -1;
        }
        
        // 如果之前正在播放，则继续播放
        if (wasPlaying && currentTrackIndex >= 0) {
            try {
                mediaPlayer.reset();
                mediaPlayer.setDataSource(this.playlist.get(currentTrackIndex).getPath());
                mediaPlayer.prepare();
                mediaPlayer.seekTo(currentPosition);
                mediaPlayer.start();
                
                // 更新曲目播放状态
                for (AudioTrack t : this.playlist) {
                    t.setPlaying(false);
                }
                this.playlist.get(currentTrackIndex).setPlaying(true);
                
                Log.d(TAG, "恢复播放: 索引=" + currentTrackIndex + ", 位置=" + currentPosition + "ms");
            } catch (IOException e) {
                Log.e(TAG, "更新播放列表后恢复播放失败: " + e.getMessage());
            }
        }
        
        // 更新通知
        updateNotification();
    }

    // 播放指定索引的曲目
    public void play(int index) {
        if (index >= 0 && index < playlist.size()) {
            // 停止当前播放
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.stop();
                try {
                    mediaPlayer.prepare();
                } catch (IOException e) {
                    Log.e(TAG, "Error preparing media player: " + e.getMessage());
                }
            }
            
            // 更新所有曲目的播放状态为非播放
            for (AudioTrack t : playlist) {
                t.setPlaying(false);
            }
            
            // 设置新的索引并重置重复计数
            currentTrackIndex = index;
            currentRepeatCount = 0;
            
            // 标记当前曲目为播放状态
            playlist.get(index).setPlaying(true);
            
            // 记录日志
            Log.d(TAG, "播放曲目，索引: " + index + ", 标题: " + 
                  (playlist.get(index) != null ? playlist.get(index).getTitle() : "未知"));
            
            // 播放新曲目
            playCurrentTrack();
        } else {
            Log.e(TAG, "无法播放：无效的索引 " + index + ", 播放列表大小: " + playlist.size());
        }
    }

    // 播放当前曲目
    private void playCurrentTrack() {
        if (currentTrackIndex < 0 || currentTrackIndex >= playlist.size()) {
            Log.e(TAG, "无法播放：无效的曲目索引 " + currentTrackIndex);
            return;
        }

        AudioTrack track = playlist.get(currentTrackIndex);
        Log.d(TAG, "开始播放曲目：" + track.getTitle() + "，路径：" + track.getPath() + "，索引：" + currentTrackIndex);
        
        try {
            mediaPlayer.reset();
            
            // 检查文件是否存在
            java.io.File file = new java.io.File(track.getPath());
            if (!file.exists()) {
                Log.e(TAG, "文件不存在：" + track.getPath());
                return;
            }
            
            Log.d(TAG, "设置数据源：" + track.getPath());
            mediaPlayer.setDataSource(track.getPath());
            
            // 检查 API 级别，只有在 API 23+ 上使用 setPlaybackParams
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                float speed = track.getPlaybackSpeed();
                Log.d(TAG, "设置播放速度：" + speed);
                
                try {
                    // 设置播放速度，最高支持到 16 倍速
                    mediaPlayer.setPlaybackParams(mediaPlayer.getPlaybackParams().setSpeed(speed));
                    Log.d(TAG, "播放速度设置成功：" + speed);
                } catch (Exception e) {
                    Log.e(TAG, "设置播放速度失败：" + e.getMessage());
                    // 如果设置失败，尝试使用较低的速度
                    if (speed > 8.0f) {
                        try {
                            float fallbackSpeed = Math.min(8.0f, speed);
                            Log.d(TAG, "尝试使用较低的播放速度：" + fallbackSpeed);
                            mediaPlayer.setPlaybackParams(mediaPlayer.getPlaybackParams().setSpeed(fallbackSpeed));
                            Log.d(TAG, "降低后的播放速度设置成功：" + fallbackSpeed);
                        } catch (Exception e2) {
                            Log.e(TAG, "设置降低后的播放速度也失败：" + e2.getMessage());
                        }
                    }
                }
            }
            
            Log.d(TAG, "设置音量：" + volume);
            mediaPlayer.setVolume(volume, volume);
            
            Log.d(TAG, "准备播放器");
            mediaPlayer.prepare();
            
            Log.d(TAG, "开始播放");
            mediaPlayer.start();
            
            // 更新所有曲目的播放状态
            for (int i = 0; i < playlist.size(); i++) {
                AudioTrack t = playlist.get(i);
                t.setPlaying(i == currentTrackIndex);
            }
            
            // 更新通知
            updateNotification();
            
            Log.d(TAG, "播放成功启动，当前播放索引：" + currentTrackIndex);
            
        } catch (IOException e) {
            Log.e(TAG, "播放错误：" + e.getMessage(), e);
        } catch (Exception e) {
            Log.e(TAG, "未知错误：" + e.getMessage(), e);
        }
    }

    // 暂停播放
    public void pause() {
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
            isPaused = true;
            updateNotification();
        }
    }

    // 恢复播放
    public void resume() {
        if (mediaPlayer != null && isPaused) {
            mediaPlayer.start();
            isPaused = false;
            updateNotification();
        }
    }

    // 停止播放
    public void stop() {
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            try {
                mediaPlayer.prepare();
            } catch (IOException e) {
                Log.e(TAG, "Error preparing media player: " + e.getMessage());
            }
            isPaused = false;
            
            // 更新所有曲目的播放状态
            for (AudioTrack t : playlist) {
                t.setPlaying(false);
            }
            
            updateNotification();
        }
    }

    // 播放下一曲
    public void playNext() {
        if (playlist.isEmpty()) {
            return;
        }
        
        currentTrackIndex = (currentTrackIndex + 1) % playlist.size();
        currentRepeatCount = 0;
        playCurrentTrack();
    }

    // 播放上一曲
    public void playPrevious() {
        if (playlist.isEmpty()) {
            return;
        }
        
        currentTrackIndex = (currentTrackIndex - 1 + playlist.size()) % playlist.size();
        currentRepeatCount = 0;
        playCurrentTrack();
    }

    // 设置音量
    public void setVolume(float volume) {
        this.volume = Math.max(0.0f, Math.min(1.0f, volume));
        if (mediaPlayer != null) {
            mediaPlayer.setVolume(this.volume, this.volume);
        }
    }
    
    // 设置播放速度
    public void setPlaybackSpeed(float speed) {
        if (currentTrackIndex >= 0 && currentTrackIndex < playlist.size()) {
            // 更新曲目对象中的播放速度
            AudioTrack track = playlist.get(currentTrackIndex);
            track.setPlaybackSpeed(speed);
            
            // 实时更新当前播放速度
            updateCurrentPlaybackSpeed(speed);
        }
    }
    
    // 设置重复次数
    public void setRepeatCount(int repeatCount) {
        if (currentTrackIndex >= 0 && currentTrackIndex < playlist.size()) {
            // 更新曲目对象中的重复次数
            AudioTrack track = playlist.get(currentTrackIndex);
            track.setRepeatCount(repeatCount);
            Log.d(TAG, "设置重复次数: " + repeatCount);
        }
    }
    
    // 更新当前播放曲目的播放速度
    public void updateCurrentPlaybackSpeed(float speed) {
        if (mediaPlayer != null && mediaPlayer.isPlaying() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            try {
                // 保存当前播放位置
                int currentPosition = mediaPlayer.getCurrentPosition();
                
                // 设置新的播放速度
                mediaPlayer.setPlaybackParams(mediaPlayer.getPlaybackParams().setSpeed(speed));
                Log.d(TAG, "实时更新播放速度成功：" + speed);
                
                // 恢复到之前的播放位置
                mediaPlayer.seekTo(currentPosition);
            } catch (Exception e) {
                Log.e(TAG, "实时更新播放速度失败：" + e.getMessage());
                // 如果设置失败，尝试使用较低的速度
                if (speed > 8.0f) {
                    try {
                        float fallbackSpeed = Math.min(8.0f, speed);
                        Log.d(TAG, "尝试使用较低的播放速度：" + fallbackSpeed);
                        mediaPlayer.setPlaybackParams(mediaPlayer.getPlaybackParams().setSpeed(fallbackSpeed));
                        Log.d(TAG, "降低后的播放速度设置成功：" + fallbackSpeed);
                    } catch (Exception e2) {
                        Log.e(TAG, "设置降低后的播放速度也失败：" + e2.getMessage());
                    }
                }
            }
        }
    }

    // 获取当前音量
    public float getVolume() {
        return volume;
    }

    // 获取当前播放的曲目
    public AudioTrack getCurrentTrack() {
        if (currentTrackIndex >= 0 && currentTrackIndex < playlist.size()) {
            return playlist.get(currentTrackIndex);
        }
        return null;
    }

    // 获取当前播放索引
    public int getCurrentTrackIndex() {
        return currentTrackIndex;
    }
    
    // 获取当前播放位置（用于在列表中显示）
    public int getCurrentPosition() {
        return currentTrackIndex;
    }

    // 是否正在播放
    public boolean isPlaying() {
        return mediaPlayer != null && mediaPlayer.isPlaying();
    }

    // 是否已暂停
    public boolean isPaused() {
        return isPaused;
    }
    
    // 获取当前播放进度（毫秒）
    public int getCurrentPlaybackPosition() {
        if (mediaPlayer != null) {
            try {
                return mediaPlayer.getCurrentPosition();
            } catch (Exception e) {
                Log.e(TAG, "获取当前播放进度失败: " + e.getMessage());
                return 0;
            }
        }
        return 0;
    }
    
    // 获取当前曲目总时长（毫秒）
    public int getCurrentTrackDuration() {
        if (mediaPlayer != null) {
            try {
                return mediaPlayer.getDuration();
            } catch (Exception e) {
                Log.e(TAG, "获取当前曲目总时长失败: " + e.getMessage());
                return 0;
            }
        }
        return 0;
    }
    
    // 获取当前曲目的总播放进度（包含重复播放的累加时长）
    public int getTotalPlaybackProgress() {
        if (mediaPlayer != null && currentTrackIndex >= 0 && currentTrackIndex < playlist.size()) {
            AudioTrack track = playlist.get(currentTrackIndex);
            int singleDuration = getCurrentTrackDuration();
            int currentPosition = getCurrentPlaybackPosition();
            
            // 计算总进度 = 已完成的重复次数 * 单次时长 + 当前播放进度
            return currentRepeatCount * singleDuration + currentPosition;
        }
        return 0;
    }
    
    // 获取当前曲目的总时长（包含重复播放的累加时长）
    public int getTotalDuration() {
        if (mediaPlayer != null && currentTrackIndex >= 0 && currentTrackIndex < playlist.size()) {
            AudioTrack track = playlist.get(currentTrackIndex);
            int singleDuration = getCurrentTrackDuration();
            
            // 计算总时长 = 重复次数 * 单次时长
            return track.getRepeatCount() * singleDuration;
        }
        return 0;
    }
    
    // 跳转到指定位置（考虑重复播放）
    public void seekToPosition(int totalPosition) {
        if (mediaPlayer != null && currentTrackIndex >= 0 && currentTrackIndex < playlist.size()) {
            AudioTrack track = playlist.get(currentTrackIndex);
            int singleDuration = getCurrentTrackDuration();
            
            if (singleDuration > 0) {
                // 计算应该处于哪个重复周期
                currentRepeatCount = totalPosition / singleDuration;
                
                // 如果超过了设定的重复次数，则限制在最后一次重复
                if (currentRepeatCount >= track.getRepeatCount()) {
                    currentRepeatCount = track.getRepeatCount() - 1;
                    // 定位到最后一次重复的结束位置附近
                    mediaPlayer.seekTo(singleDuration - 100);
                } else {
                    // 计算在当前重复周期中的位置
                    int positionInCurrentRepeat = totalPosition % singleDuration;
                    mediaPlayer.seekTo(positionInCurrentRepeat);
                }
                
                Log.d(TAG, "跳转到位置: 总位置=" + totalPosition + "ms, 重复次数=" + currentRepeatCount + 
                        ", 当前周期内位置=" + (totalPosition % singleDuration) + "ms");
            }
        }
    }

    // 更新通知
    private void updateNotification() {
        // 检查是否有通知权限（Android 13及以上版本需要）
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            // 对于Android 13及以上版本，我们需要检查POST_NOTIFICATIONS权限
            // 但由于Service不能直接请求权限，我们只能在有权限时发送通知
            if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.POST_NOTIFICATIONS) 
                    == PackageManager.PERMISSION_GRANTED) {
                NotificationManager notificationManager = 
                        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                notificationManager.notify(NOTIFICATION_ID, createNotification());
            } else {
                Log.w(TAG, "没有通知权限，无法更新通知");
                // 在实际应用中，您可能需要通过MainActivity请求权限
            }
        } else {
            // 对于Android 12及以下版本，不需要特殊权限
            NotificationManager notificationManager = 
                    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.notify(NOTIFICATION_ID, createNotification());
        }
    }
}